package cn.yogehaoren.foxgitstarter.config;


import cn.yogehaoren.foxgitstarter.common.Constants;
import cn.yogehaoren.foxgitstarter.controller.FoxGitController;
import cn.yogehaoren.foxgitstarter.properties.GitProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author WangNing
 * date  2021/8/5 0:00
 * @version 1.0
 */
@ConditionalOnWebApplication
@ConditionalOnProperty(name = {Constants.ENABLE_WEB_HOOK})
@Configuration
@Slf4j
public class FoxGitControllerConfig {

    @Autowired
    private GitProperties gitProperties;

    /**
     * 动态添加 Mapping
     * @link https://docs.spring.io/spring-framework/docs/current/reference/html/web.html
     * @param foxGitController -
     * @param requestMappingHandlerMapping -
     * @throws NoSuchMethodException -
     */
    @Autowired
    public void registerWebHookMapping(FoxGitController foxGitController, RequestMappingHandlerMapping requestMappingHandlerMapping) throws NoSuchMethodException {

        RequestMappingInfo requestMappingInfo = RequestMappingInfo
                .paths(gitProperties.getProcessWebHookUrl())
                .methods(RequestMethod.POST)
                .produces(MediaType.APPLICATION_JSON_VALUE)
                .build();
        log.info("Fox Git 添加 WebHookUrl: {} [header:\"{}\" token: \"{}\"]", gitProperties.getProcessWebHookUrl(), gitProperties.getWebHookHeader(), gitProperties.getWebHookToken());
        requestMappingHandlerMapping.
                registerMapping(requestMappingInfo, foxGitController,
                        FoxGitController.class.getDeclaredMethod("handleWebHook", HttpServletRequest.class, HttpServletResponse.class, String.class)
                );

    }

}
